package com.shujia.spark.stream

import org.apache.spark.SparkContext
import org.apache.spark.rdd.RDD
import org.apache.spark.sql.{DataFrame, SparkSession}
import org.apache.spark.streaming.dstream.{DStream, ReceiverInputDStream}
import org.apache.spark.streaming.{Durations, StreamingContext}

object Demo3DrddToDS {
  def main(args: Array[String]): Unit = {

    /**
      * 1、创建spark环境
      *
      */

    val spark: SparkSession = SparkSession
      .builder()
      .master("local[2]")
      .appName("dstordd")
      .config("spark.sql.shuffle.partitions", 1)
      .getOrCreate()

    import org.apache.spark.sql.functions._
    import spark.implicits._

    val sc: SparkContext = spark.sparkContext

    /**
      * 创建SparkStreaming环境
      *  Durations.seconds(5): 多久执行一次
      *
      */

    val ssc = new StreamingContext(sc, Durations.seconds(5))

    val linesDS: ReceiverInputDStream[String] = ssc.socketTextStream("master", 8888)


    /**
      * transform: 传进去一个rdd返回一个rdd,
      * 每隔一段时间执行一次
      *
      */
    val wordDS: DStream[(String, Int)] = linesDS.transform(rdd => {
      println("transform")

      val resultRDD: RDD[(String, Int)] = rdd.flatMap(_.split(","))
        .map((_, 1))
        .reduceByKey(_ + _)

      resultRDD
    })


    wordDS.print()

    ssc.start()
    ssc.awaitTermination()
    ssc.stop()

  }

}
